<template>
  <div class="page-miH page-bgBack">
    <a-spin :spinning="loading">
      <div style="margin-top: 24px; display: flex">
        <div class="optionalFieldsBox">
          <div class="optionalFieldsLeft">可选字段</div>
          <div style="margin-top: 12px; display: flex; flex-wrap: wrap">
            <a-button
              :disabled="!item.canUpdate"
              v-for="(item, index) in fieldList"
              :key="index"
              @click="addField(item)"
              class="optionalFieldsLAddField"
            >
              <span
                v-if="item.isChecked"
                class="icon iconfont icon-xuanzhong iconShow"
                style="position: absolute; top: -11px; right: 0"
              ></span>
              {{ item.fieldName }}
            </a-button>
          </div>
        </div>
        <div style="width: 100%">
          <a-form v-if="siteFieldList" :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
            <draggable v-model="siteFieldList" group="itxst" animation="300" filter=".undraggable" :move="onMove">
              <div
                v-for="(item, index) in siteFieldList"
                :key="index"
                style="cursor: move"
                :class="canUpdateArr.includes(item.enName) ? 'undraggable' : 'draggable'"
              >
                <div>
                  <a-row class="rigBox">
                    <a-col :span="1" class="hei56" v-if="!canUpdateArr.includes(item.enName)">
                      <a-icon class="tableIcon" type="unordered-list" />
                    </a-col>
                    <a-col :span="1" class="hei56" v-else></a-col>
                    <a-col :span="17" class="hei56">
                      <a-row>
                        <a-col :span="21" style="margin-top: 9px">
                          <XqItem ref="XqItem" :editable="true" :form="form" :dataSource="basicData" :item="formField[item.enName]" />
                        </a-col>

                        <a-col :span="3" v-if="!canUpdateArr.includes(item.enName)">
                          <a-checkbox v-model="item.isNecessary" @change="necessaryChange(item)">必填</a-checkbox>
                        </a-col>
                      </a-row>
                    </a-col>
                    <a-col :span="6" class="parelative">
                      <div class="paAbsolut" v-if="!canUpdateArr.includes(item.enName)">
                        <a-icon type="close" @click="delClose(item, index)" class="tableIcon1" />
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </draggable>
          </a-form>
        </div>
      </div>
      <div class="bottomButton">
        <a-button type="primary" @click="saveData">保存</a-button>
      </div>
    </a-spin>
  </div>
</template>

<script>
import {
  selectByCustomTemplateType,
  selectOneByTypeAndId,
  editCustomTemplate,
  findByDefaultType,
  findBySite,
  findBySiteCustomTemplates,
  findByTemplateId
} from "./api";
import draggable from "vuedraggable";
import XqFormMixin from "xqjr-plugin-form/mixins/XqFormMixin";
const FormMixin = XqFormMixin();
export default {
  components: { draggable },
  mixins: [FormMixin],
  computed: {
    formField() {
      return this.formFieldL;
    },
    basicData() {
      return this.basicDataL;
    }
  },
  props: {
    typeVal: {
      type: String,
      default: ""
    }
  },
  watch: {
    typeVal: {
      handler(val) {
        if (val) {
          this.findByDefault();
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      fieldList: [],
      siteFieldList: [],
      basicDataL: {},
      QrCode: "",
      formFieldL: null,
      loading: false,
      canUpdateArr: [],
      findBySiteField: {}
    };
  },
  created() {},
  methods: {
    onMove(e) {
      if (this.canUpdateArr.includes(e.relatedContext.element.enName)) {
        return false;
      }
      return true;
    },
    getFormJson(z, status) {
      const message =
        z.type === "input" || z.fieldType === "textarea" || z.fieldType === "idCard" || z.fieldType === "phone"
          ? `请输入${JSON.parse(z.formJson)[z.enName].wrapper.label}`
          : `请选择${JSON.parse(z.formJson)[z.enName].wrapper.label}`;
      const decorator = JSON.parse(z.formJson)[z.enName].decorator
        ? JSON.parse(z.formJson)[z.enName].decorator
        : (JSON.parse(z.formJson)[z.enName].decorator = {});
      if (decorator.rules && decorator.rules.length !== 0) {
        decorator.rules[0] = {
          required: status,
          message: message
        };
      } else {
        decorator.rules = [
          {
            required: status,
            message: message
          }
        ];
      }
      return { [z.enName]: { ...JSON.parse(z.formJson)[z.enName], ...{ decorator: decorator } } };
    },
    // 保存
    saveData() {
      const arr = this.siteFieldList.map((z, index) => {
        z.sort = index + 1;
        z.formJson = z.isNecessary ? JSON.stringify(this.getFormJson(z, true)) : JSON.stringify(this.getFormJson(z, false));
        return z;
      });
      let data = {};
      if (this.typeVal !== "SweepCodeEntry") {
        data = {
          fieldList: arr,
          subjectType: this.typeVal === "tenant" ? "site" : "recruit",
          type: this.findBySiteField.type,
          subjectId: this.typeVal === "tenant" ? localStorage.getItem("siteId") : this.$route.query.id,
          name: this.findBySiteField.name,
          templateId: this.findBySiteField.id
        };
      } else {
        data = {
          fieldList: arr,
          subjectType: "site",
          subjectId: localStorage.getItem("siteId"),
          templateId: this.siteFieldList[0].templateId
        };
      }
      editCustomTemplate(data).then((res) => {
        this.$notification["success"]({
          message: "success",
          description: "保存成功"
        });
        this.findByDefault();
        this.$emit("ok");
      });
    },
    necessaryChange(item) {
      this.setdata(this.siteFieldList);
    },
    // 添加模板字段
    addField(e) {
      e.isChecked = true;
      var hasItem = false;
      this.siteFieldList.forEach((item, index) => {
        // hasItem = false;
        if (item.enName === e.enName) {
          hasItem = true;
        }
      });
      if (hasItem === false) {
        this.siteFieldList.push(e);
        this.siteFieldList = JSON.parse(JSON.stringify(this.siteFieldList));
        this.setdata(this.siteFieldList);
        this.getFixed();
      } else {
        this.siteFieldList = this.siteFieldList.filter((z) => z.enName !== e.enName);
        this.fieldList.forEach((item, index) => {
          if (item.enName === e.enName) {
            item.isChecked = false;
          }
        });
      }
    },
    // 固定表头
    getFixed() {
      this.canUpdateArr = this.siteFieldList.map((z) => {
        if (!z.canUpdate) {
          return z.enName;
        }
      });
      this.canUpdateArr = this.canUpdateArr.filter((s) => {
        return s && s.trim();
      });
    },
    // 删除模板字段
    delClose(e, index) {
      this.siteFieldList.splice(index, 1);
      this.fieldList.forEach((item, index) => {
        if (item.enName === e.enName) {
          item.isChecked = false;
        }
      });
    },
    // 获取系统模板的字段项
    findByDefault() {
      this.loading = true;
      let request = null;
      if (this.typeVal === "SweepCodeEntry") {
        request = selectByCustomTemplateType({
          customTemplateType: "recruit2Input2",
          subjectType: "site",
          subjectId: localStorage.getItem("siteId")
        });
      } else if (this.typeVal === "tenant") {
        request = selectByCustomTemplateType({
          customTemplateType: "recruit2Delivery2",
          subjectType: "site",
          subjectId: localStorage.getItem("siteId")
        });
      } else if (this.typeVal === "jobs") {
        request = selectByCustomTemplateType({
          customTemplateType: "recruit2Delivery2",
          subjectType: "recruit",
          subjectId: this.$route.query.id
        });
      }
      request
        .then((res) => {
          this.fieldList = res.data.map((z) => {
            z.fieldName = z.formJson ? JSON.parse(z.formJson)[z.enName].wrapper.label : z.fieldName;
            return z;
          });
          this.findBySite();
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 获取租户模板
    async findBySite() {
      let data = {};
      let request = null;
      // 租户tenant，投递jobs，扫码SweepCodeEntry
      if (this.typeVal === "tenant") {
        data = { type: "recruit2Delivery2", subjectType: "site", subjectId: localStorage.getItem("siteId") };
        request = selectOneByTypeAndId(data);
      } else if (this.typeVal === "jobs") {
        data = { type: "recruit2Delivery2", subjectType: "recruit", subjectId: this.$route.query.id };
        request = selectOneByTypeAndId(data);
      } else if (this.typeVal === "SweepCodeEntry") {
        request = findBySiteCustomTemplates({ type: "recruit2Input2" });
      }
      request
        .then((res) => {
          this.findBySiteField = res.data;
          this.siteFieldList = res.data.customTemplateFieldListVOList;
          this.setdata(this.siteFieldList);
          this.siteFieldList.forEach((item, index) => {
            item.required = item.isNecessary;
            this.fieldList.forEach((item2, index2) => {
              if (item2.enName === item.enName) {
                item2.isChecked = true;
              }
            });
          });
          this.getFixed();
          this.fieldList = JSON.parse(JSON.stringify(this.fieldList));
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 处理字段类型
    setdata(element) {
      const fieldKeys = element.map((z) => z.enName);
      const fields = {};
      element.forEach((item, index) => {
        item.formJson = item.isNecessary ? JSON.stringify(this.getFormJson(item, true)) : JSON.stringify(this.getFormJson(item, false));
        if (item.formJson) {
          fields[item.enName] = JSON.parse(item.formJson)[item.enName];
        }
      });
      this.formFieldL = fields;
      this.$nextTick(() => {
        const data = fieldKeys.reduce((res, key) => {
          res[key] = null;
          return res;
        }, {});
        this.basicDataL = data;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.iconShow {
  color: var(--primary);
}
.optionalFieldsBox {
  min-width: 360px;
  width: 360px;
  min-height: 500px;
  border-right: 1px solid #e8e8e8;
  padding-right: 24px;
}
.optionalFieldsLeft {
  font-size: 16px;
  font-weight: 500;
  color: #3c3d43;
  border-bottom: 1px solid #e8e8e8;
  padding: 18px 0 18px 0;
}
.optionalFieldsLAddField {
  width: 150px;
  height: 38px;
  border-radius: 4px;
  border: 1px solid #dfdfdf;
  margin-top: 12px;
  margin-right: 12px;
  text-align: center;
  line-height: 38px;
  cursor: pointer;
  position: relative;
}
.bottomButton {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 56px;
  background: #ffffff;
  box-shadow: inset 0px 1px 0px 0px #e8e8e8;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.hei56 {
  min-height: 56px;
  line-height: 56px;
}
.rigBox {
  margin: 0 24px;
  border-radius: 4px;
  padding: 0 0 14px 14px;
  padding-bottom: 4px;
  width: 99%;
}
.rigBox:hover {
  background: #ffffff;
  box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.1);
  border: 1px dashed var(--primary);

  .dn {
    display: inline-block;
  }
}
.tableIcon1 {
  font-size: 13px;
  width: 24px;
  height: 24px;
  background: var(--primary);
  border-radius: 0px 4px 0px 4px;
  color: #fff;
  line-height: 24px;
}
.dn {
  display: none;
}
.parelative {
  position: relative;
}
.paAbsolut {
  position: absolute;
  top: 0;
  right: 0;
}
.tableIcon {
  width: 13px;
  height: 11px;
  color: var(--primary);
  margin-right: 8px;
}
</style>
